import React, {useCallback, useEffect, useState} from 'react';
import {Breadcrumb, Button, Form, Input, message, Modal, Space, Table, TableProps} from 'antd';
import {useNavigate} from "react-router-dom";
import type {WorkExperience} from "@/types/resp/workExperience";
import workExperienceApi from '@/api/workExperienceApi'
import {Result} from "@/types/result";
import {Page} from "@/types/page";
import WorkExperienceAdd from "@/pages/workExperience/WorkExperienceAdd.tsx";
import WorkExperienceView from "@/pages/workExperience/WorkExperienceView.tsx";
import EmployeeSelector from "@/pages/employee/EmployeeSelector.tsx";
import { exportToExcel } from '@/utils/exportUtil.ts'



const WorkExperienceList: React.FC = () => {

  const navigate = useNavigate();
  const [messageApi, messageContextHolder] = message.useMessage();
  const [modal, modalContextHolder] = Modal.useModal();

  const handleClick = (path: string) => {
    navigate(path);
  };

  const breadcrumbsItems = [
    {title: '首页', className: 'breadcrumbHome', onClick: () => handleClick('/Home')},
    {title: '工作经历列表'}
  ]

  const [form] = Form.useForm();

  const onFinish = async () => {
    await onSearch()
  };

  const onReset = () => {
    form.resetFields();
  };

  const [data, setData] = useState<WorkExperience[]>([]);
  const onSearch = async () => {
    try {
      const resp: Result<Page<WorkExperience>> = await workExperienceApi.find(form.getFieldsValue())
      if (resp && resp.code === 1) {
        if (resp.data) {
          const page: Page<WorkExperience> = resp.data
          if (page && page.list.length > 0) {
            setData(page.list)
          }
        }
      }
    } catch (e) {
      console.log('获取数据异常', e)
    }
  };

  const columns: TableProps<WorkExperience>['columns'] = [
    {title: '员工姓名', dataIndex: 'employeeName', key: 'employeeName'},
    {title: '公司名称', dataIndex: 'company', key: 'company'},
    {title: '岗位', dataIndex: 'position', key: 'position'},
    {title: '开始日期', key: 'startDate', render: (_, record) => (
      <div>{record.startDate ? record.startDate.format('YYYY-MM-DD') : ''}</div>
    )},
    {title: '结束日期', key: 'endDate', render: (_, record) => (
      <div>{record.endDate ? record.endDate.format('YYYY-MM-DD') : ''}</div>
    )},
    {title: '岗位职责', dataIndex: 'responsibilities', key: 'responsibilities', ellipsis: true},
    {
      title: '操作',
      key: 'action',
      width: '250px',
      render: (_, record) => (
        <Space size="middle">
          <Button type="primary" onClick={() => editRow(record.id)}>编辑</Button>
          <Button danger onClick={() => delRow(record.id)}>删除</Button>
          <Button color="primary" variant="outlined" onClick={() => detailRow(record)}>详情</Button>
        </Space>
      ),
    },
  ];

  const [workExperienceAddVisible, setWorkExperienceAddVisible] = useState(false);
  const [workExperienceViewVisible, setWorkExperienceViewVisible] = useState(false);
  const [selectedWorkExperienceId, setSelectedWorkExperienceId] = useState(0)
  const [selectedWorkExperience, setSelectedWorkExperience] = useState({})

  const onAdd = () => {
    setSelectedWorkExperienceId(0)
    setWorkExperienceAddVisible(true)
  };

  const editRow = (id: number) => {
    setSelectedWorkExperienceId(id)
    setWorkExperienceAddVisible(true)
  };

  const delRow = useCallback(async (id: number) => {
    const confirmed = await modal.confirm({
      title: '删除提示',
      content: (
        <>
          确定要删除吗?
        </>
      ),
      okText: '确定',
      cancelText: '取消',
      type: 'warning'
    });

    if (confirmed) {
      workExperienceApi.del(id)
        .then((resp) => {
          if (resp && resp.code === 1) {
            messageApi.success('删除成功!')
            onSearch()
          } else {
            messageApi.error('操作失败:' + (resp.msg ? resp.msg : '原因未知'))
          }
        })
        .catch(error => {
          console.error('操作失败:', error)
        })
    }
  }, [modal]);

  const detailRow = (record: WorkExperience) => {
    setSelectedWorkExperience(record)
    setWorkExperienceViewVisible(true)
  };

  const [employeeSelectorVisible, setEmployeeSelectorVisible] = useState(false);
  const findEmployee = () => {
    setEmployeeSelectorVisible(true);
  }
  const handleEmployeeSelected = (selectedEmployee: { employeeId?: number; employeeName?: string; }) => {
    setEmployeeSelectorVisible(false)
    if (selectedEmployee && 'employeeId' in selectedEmployee) {
      form.setFieldsValue(Object.assign(form.getFieldsValue(), {
      employeeId: selectedEmployee['employeeId'],
      employeeName: selectedEmployee['employeeName'],
      }));
    }
  };
  const handleCloseEmployeeSelector = () => {
    setEmployeeSelectorVisible(false)
  };

  const handleCloseWorkExperienceAdd = () => {
    setWorkExperienceAddVisible(false)
  };

  const handleCloseWorkExperienceView = () => {
    setWorkExperienceViewVisible(false)
  };

  const onExport = () => {
    const headers = ['员工姓名','公司名称','岗位','开始日期','结束日期','岗位职责']
    workExperienceApi.find(form.getFieldsValue()).then(data => {
      if (!data || !data.data || data.data.list.length < 1) {
        messageApi.error('无数据导出')
        return
      }
      const exportData = []
      for (const d of data.data.list) {
        exportData.push([d.employeeName,d.company,d.position,d.startDate,d.endDate,d.responsibilities])
      }
      exportToExcel(headers, exportData)
    })
  }

  useEffect(() => {
    onSearch();

    return () => {
    };
  }, []);

  return (
    <div className="workExperienceList">
      {messageContextHolder}
      {modalContextHolder}
      <Breadcrumb items={breadcrumbsItems} style={{marginBottom: 'var(--container-margin)'}} />
      <Form form={form} onFinish={onFinish} layout={"inline"}>
        <Form.Item name="employeeName" label="员工姓名">
          <Input.Search placeholder="请选择员工姓名" onSearch={findEmployee} readOnly={true} />
        </Form.Item>
        <Form.Item label={null}>
          <Button type="primary" htmlType="submit">查询</Button>
        </Form.Item>
        <Form.Item label={null}>
          <Button onClick={onReset}>重置</Button>
        </Form.Item>
        <Form.Item label={null}>
          <Button type="primary" onClick={onAdd}>新增</Button>
        </Form.Item>
        <Form.Item label={null}>
          <Button type="primary" onClick={onExport}>导出</Button>
        </Form.Item>
      </Form>
      <Table<WorkExperience> columns={columns} dataSource={data} size="small" rowKey={record => record.id} pagination={{ position: ["bottomCenter"] }} style={{marginTop: 'var(--container-margin)'}} />
      <EmployeeSelector visible={employeeSelectorVisible} onEmployeeSelected={handleEmployeeSelected} onCloseEmployeeSelector={handleCloseEmployeeSelector} />
      <WorkExperienceAdd visible={workExperienceAddVisible} onCloseWorkExperienceAdd={handleCloseWorkExperienceAdd} id={selectedWorkExperienceId} />
      <WorkExperienceView visible={workExperienceViewVisible} onCloseWorkExperienceView={handleCloseWorkExperienceView} viewRow={selectedWorkExperience} />
    </div>
  );
};

export default WorkExperienceList;
